package com.moba.scheduler;

import com.moba.domain.*;
import com.moba.emums.*;
import com.moba.emums.orderInfo.OrderState;
import com.moba.emums.roleUser.UserType;
import com.moba.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Component
public class ScheduledTask {
  @Autowired UserInfoService userInfoService;

  @Autowired BaseDataService baseDataService;

  @Autowired OrderInfoService orderInfoService;

  @Autowired SysSettingService sysSettingService;

  @Autowired UserRelationService userRelationService;

  protected static final Logger logger = LoggerFactory.getLogger(ScheduledTask.class);

  // 分红奖励  每十分钟跑一次
  @Scheduled(cron = "0 0/10 0 * * ?")
  //    @Scheduled(cron = "30 * * * * ?")每三十秒跑一次
  public void orderPriceJob() throws Exception {
    logger.info("===orderPriceJob===start");
    int 订单轮回天数 = 5;

    // 查询系统设置轮回天数
    SysSetting sys = new SysSetting();
    sys.setMemo(SysSettingType.dayCountRetrun.getName());
    sys = sysSettingService.getEntity(sys);
    if (null != sys) {
      订单轮回天数 = Integer.valueOf(sys.getContent());
    }

    // 订单出金比例
    sys = new SysSetting();
    sys.setMemo(SysSettingType.orderProfitRatio.getIndex());
    BigDecimal 订单出金比例 =
        new BigDecimal(sysSettingService.getEntity(sys).getContent()).divide(new BigDecimal(100));

    // 查出所有用户
    UserInfo userInfo = new UserInfo();
    userInfo.setIsDel(0);
    userInfo.setUserType(UserType.USER_TYPE_2.getIndex());
    //    userInfo.getMap().put("order_count_gt_0", "true");
    List<UserInfo> userInfoList = userInfoService.getEntityList(userInfo);
    if (null == userInfoList || userInfoList.size() == 0) {
      return;
    }

    userInfoList:
    for (UserInfo item : userInfoList) {
      // 用户所有订单
      OrderInfo orderInfo = new OrderInfo();
      orderInfo.setAddUserId(item.getId());
      orderInfo.setOrderState(OrderState.ORDER_STATE_10.getIndex());
      //      order.getMap().put("order_by_order_money_desc", "true");
      List<OrderInfo> orderInfoList = orderInfoService.getEntityList(orderInfo);
      if (null == orderInfoList || orderInfoList.size() == 0 || orderInfoList.size() < 订单轮回天数) {
        continue;
      }

      // 获取当前用户有几轮订单
      List<OrderInfo> tempList = orderInfoService.getDistinctTempList(orderInfo);

      // 获取有几轮
      int 轮数余数 = orderInfoList.size() % 订单轮回天数;
      logger.info("轮数余数:" + 轮数余数);
      //      int 轮数 = (orderInfoList.size() - 轮数余数) / 订单轮回天数;
      int 轮数 = tempList.size();
      logger.info("轮数:" + 轮数);

      // 判断当前用户订单是否锁定
      // 最后一个订单金额是不是最大的

      // 获取当前收益的订单
      OrderInfo 收益订单 = orderInfoList.get(0);

      // 判断当前订单是否满了一个轮回
      OrderInfo tempOrder = new OrderInfo();
      tempOrder.setTemp(收益订单.getTemp());
      List<OrderInfo> tempOrderList = orderInfoService.getEntityList(tempOrder);
      // 订单不满足一个轮回数直接跳过
      if (null == tempOrderList || tempOrderList.size() == 0 || tempOrderList.size() != 订单轮回天数) {
        continue;
      }

      boolean 是否出单 = false;

      // 判断当前轮回中是否锁定
      BigDecimal 当前轮回中最大金额 = new BigDecimal(0);
      for (int i = 0; i < tempOrderList.size() - 1; i++) {
        OrderInfo a = tempOrderList.get(i);
        if (当前轮回中最大金额.compareTo(a.getOrderMoney()) < 0) {
          当前轮回中最大金额 = a.getOrderMoney();
        }
      }
      BigDecimal 轮回中最后一单金额 = tempOrderList.get(tempOrderList.size()).getOrderMoney();

      if (当前轮回中最大金额.compareTo(轮回中最后一单金额) >= 0) {
        是否出单 = true;
      }
      if (!是否出单) {
        // 不出单直接跳到下个用户
        logger.info("===不出单===");
        //        continue;
        // 当前轮回不出单，再判断是否有别的轮订单

        if (轮数 > 1) {
          // 上一轮中订单被锁定，在后面的订单中判断是否能出单
          tempList:
          for (OrderInfo a : tempList) {
            String tempIndex = a.getTemp();
            OrderInfo thisTempOrder = new OrderInfo();
            thisTempOrder.setTemp(tempIndex);
            List<OrderInfo> thisTempOrderList = orderInfoService.getEntityList(thisTempOrder);
            thisTempOrderList:
            for (OrderInfo b : thisTempOrderList) {
              if (当前轮回中最大金额.compareTo(a.getOrderMoney()) <= 0) {
                是否出单 = true;
                break tempList;
              }
            }
          }
        } else {
          continue userInfoList;
        }
      }
      if (!是否出单) {
        // 不出单直接跳到下个用户
        logger.info("===不出单===");
        continue;
      }

      BigDecimal 收益金额 = 收益订单.getOrderMoney().multiply(new BigDecimal(订单轮回天数)).multiply(订单出金比例);

      收益订单.setOrderState(OrderState.ORDER_STATE_50.getIndex());
      收益订单.setFahuoDate(new Date()); // 发放奖励时间
      收益订单.getMap().put("send_gusd", 收益金额);
      orderInfoService.updateEntity(收益订单);
    }

    //    OrderInfo order = new OrderInfo();
    //    order.setOrderState(OrderState.ORDER_STATE_10.getIndex());
    //    order.getMap().put("orderDateDiffGt", 订单轮回天数); // 默认三天一轮发放奖励
    //    List<OrderInfo> orderList = orderInfoService.getEntityList(order);
    //    if (null != orderList && orderList.size() > 0) {
    //
    //      for (OrderInfo temp : orderList) {
    //
    //        temp.setOrderState(OrderState.ORDER_STATE_50.getIndex());
    //        temp.setFahuoDate(new Date()); // 发放奖励时间
    //
    //        // 获取排单分红奖励比例
    //        BaseData baseData = new BaseData();
    //        baseData.setType(BaseDataType.BaseDataType_50.getIndex());
    //        baseData.setValue(temp.getOrderType().toString());
    //        baseData = baseDataService.getEntity(baseData);
    //
    //        BigDecimal bonus =
    //            temp.getOrderMoney().multiply(new BigDecimal(baseData.getPreData())); // 分红
    //        // 订单分红存入记录
    //        temp.setProfitMoney(bonus);
    //        temp.getMap().put("send_price", bonus);
    //        orderInfoService.updateEntity(temp);
    //      }
    //    }
    logger.info("===orderPriceJob===end");
  }

  // 用户升级并发放同级奖励 0:50
  @Scheduled(cron = "0 50 0 * * ?")
  public void userLeveUp() throws Exception {
    logger.info("===userLeveUp===start");
    BigDecimal yeji = new BigDecimal(String.valueOf(500000));

    // 成为k1的业绩
    BaseData base = new BaseData();
    base.setId(UserLevel.USER_LEVEL_201.getIndex());
    base = baseDataService.getEntity(base);
    if (base != null && base.getPreData() != null) {
      yeji = new BigDecimal(base.getPreData());
    }

    // 成为k2的业绩
    BigDecimal invit_count = new BigDecimal(3);
    BaseData baseData = new BaseData();
    baseData.setId(UserLevel.USER_LEVEL_202.getIndex());
    BaseData baseData_k2 = baseDataService.getEntity(baseData);
    if (baseData_k2 != null && baseData_k2.getPreData() != null) {
      invit_count = new BigDecimal(baseData_k2.getPreData());
    }

    BigDecimal yeji_k2 = yeji.multiply(invit_count);

    // 成为k3的业绩
    baseData.setId(UserLevel.USER_LEVEL_203.getIndex());
    BaseData baseData_k3 = baseDataService.getEntity(baseData);
    if (baseData_k3 != null && baseData_k3.getPreData() != null) {
      invit_count = new BigDecimal(baseData_k3.getPreData());
    }
    BigDecimal yeji_k3 = yeji_k2.multiply(invit_count);

    // 成为k4的业绩
    baseData.setId(UserLevel.USER_LEVEL_204.getIndex());
    BaseData baseData_k4 = baseDataService.getEntity(baseData);
    if (baseData_k4 != null && baseData_k4.getPreData() != null) {
      invit_count = new BigDecimal(baseData_k4.getPreData());
    }
    BigDecimal yeji_k4 = yeji_k3.multiply(invit_count);

    // 升级普通用户
    UserInfo user = new UserInfo();
    user.setIsDel(0);
    user.getMap().put("leiji_money_user_gt", yeji);
    user.getMap().put("user_level_lt", UserLevel.USER_LEVEL_201.getIndex());
    List<UserInfo> userList = userInfoService.getEntityList(user);

    if (null != userList && userList.size() > 0) {
      BaseData data = new BaseData();
      data.setType(BaseDataType.BaseDataType_70.getIndex());
      data.setLinkId(UserLevel.USER_LEVEL_201.getIndex());
      data = baseDataService.getEntity(data);

      BigDecimal levelUpPrice_rate = new BigDecimal(data.getValue());
      BigDecimal levelUpPrice_k1 = yeji.multiply(levelUpPrice_rate);

      for (UserInfo tempUser : userList) {

        UserRelation userRelation = new UserRelation();
        userRelation.setUserParId(tempUser.getId());
        int invite_count = userRelationService.getEntityCount(userRelation);
        if (invite_count >= Integer.valueOf(base.getValue())) { // 直推20人

          tempUser.setUserLevel(UserLevel.USER_LEVEL_201.getIndex());
          tempUser.setUpdateDate(new Date());
          // 同级奖励
          tempUser.getMap().put("send_tongji_price", true);
          // 升级奖励
          userInfoService.updateBi(
              tempUser.getId(),
              tempUser.getId(),
              BiGetType.BI_GET_TYPE_60.getIndex(),
              BiType.BI_TYPE_300.getIndex(),
              BiChuOrRu.BI_CHU_OR_RU_1.getIndex(),
              levelUpPrice_k1,
              null);
          userInfoService.updateEntity(tempUser);
        }
      }
    }

    // 升级k1,k2,k3,k4的用户
    UserInfo userInfo = new UserInfo();
    userInfo.setIsDel(0);
    userInfo.getMap().put("user_level_in", "201,202,203,204");
    List<UserInfo> list = userInfoService.getEntityList(user);

    if (null != list && list.size() > 0) {
      for (UserInfo tempUser : userList) {

        switch (tempUser.getUserLevel()) {
          case 201:
            boolean can_level_up1 =
                userInfoService.userLevelCount(
                    tempUser.getId(), UserLevel.USER_LEVEL_201.getIndex());
            if (can_level_up1) {
              tempUser.setUserLevel(UserLevel.USER_LEVEL_202.getIndex());
              tempUser.setUpdateDate(new Date());
              tempUser.getMap().put("send_tongji_price", true);

              // 升级奖励
              BaseData data = new BaseData();
              data.setType(BaseDataType.BaseDataType_70.getIndex());
              data.setLinkId(UserLevel.USER_LEVEL_202.getIndex());
              data = baseDataService.getEntity(data);

              BigDecimal levelUpPrice_rate = new BigDecimal(data.getValue());
              BigDecimal levelUpPrice_k2 = yeji_k2.multiply(levelUpPrice_rate);

              userInfoService.updateBi(
                  tempUser.getId(),
                  tempUser.getId(),
                  BiGetType.BI_GET_TYPE_60.getIndex(),
                  BiType.BI_TYPE_300.getIndex(),
                  BiChuOrRu.BI_CHU_OR_RU_1.getIndex(),
                  levelUpPrice_k2,
                  null);

              userInfoService.updateEntity(tempUser);
            }
            break;
          case 202:
            boolean can_level_up2 =
                userInfoService.userLevelCount(
                    tempUser.getId(), UserLevel.USER_LEVEL_202.getIndex());
            if (can_level_up2) {
              tempUser.setUserLevel(UserLevel.USER_LEVEL_203.getIndex());
              tempUser.setUpdateDate(new Date());
              tempUser.getMap().put("send_tongji_price", true);

              // 升级奖励
              BaseData data = new BaseData();
              data.setType(BaseDataType.BaseDataType_70.getIndex());
              data.setLinkId(UserLevel.USER_LEVEL_203.getIndex());
              data = baseDataService.getEntity(data);

              BigDecimal levelUpPrice_rate = new BigDecimal(data.getValue());
              BigDecimal levelUpPrice_k3 = yeji_k3.multiply(levelUpPrice_rate);

              userInfoService.updateBi(
                  tempUser.getId(),
                  tempUser.getId(),
                  BiGetType.BI_GET_TYPE_60.getIndex(),
                  BiType.BI_TYPE_300.getIndex(),
                  BiChuOrRu.BI_CHU_OR_RU_1.getIndex(),
                  levelUpPrice_k3,
                  null);
              userInfoService.updateEntity(tempUser);
            }

            break;
          case 203:
            boolean can_level_up3 =
                userInfoService.userLevelCount(
                    tempUser.getId(), UserLevel.USER_LEVEL_203.getIndex());
            if (can_level_up3) {
              tempUser.setUserLevel(UserLevel.USER_LEVEL_204.getIndex());
              tempUser.setUpdateDate(new Date());
              tempUser.getMap().put("send_tongji_price", true);
              // 升级奖励
              BaseData data = new BaseData();
              data.setType(BaseDataType.BaseDataType_70.getIndex());
              data.setLinkId(UserLevel.USER_LEVEL_204.getIndex());
              data = baseDataService.getEntity(data);

              BigDecimal levelUpPrice_rate = new BigDecimal(data.getValue());
              BigDecimal levelUpPrice_k4 = yeji_k4.multiply(levelUpPrice_rate);

              userInfoService.updateBi(
                  tempUser.getId(),
                  tempUser.getId(),
                  BiGetType.BI_GET_TYPE_60.getIndex(),
                  BiType.BI_TYPE_300.getIndex(),
                  BiChuOrRu.BI_CHU_OR_RU_1.getIndex(),
                  levelUpPrice_k4,
                  null);
              userInfoService.updateEntity(tempUser);
            }
            break;
          default:
            boolean can_level_up4 =
                userInfoService.userLevelCount(
                    tempUser.getId(), UserLevel.USER_LEVEL_204.getIndex());
            if (can_level_up4) {
              //
              //              tempUser.setUserLevel(UserLevel.USER_LEVEL_205.getIndex());
              //              tempUser.setUpdateDate(new Date());
              //              tempUser.getMap().put("send_tongji_price", true);
              //
              //              // 升级奖励
              //              BaseData data = new BaseData();
              //              data.setType(BaseDataType.BaseDataType_70.getIndex());
              //              data.setLinkId(UserLevel.USER_LEVEL_205.getIndex());
              //              data = baseDataService.getEntity(data);
              //
              //              BigDecimal levelUpPrice_rate = new BigDecimal(data.getValue());
              //              BigDecimal levelUpPrice_k5 = yeji_k5.multiply(levelUpPrice_rate);
              //
              //              userInfoService.updateBi(
              //                  tempUser.getId(),
              //                  tempUser.getId(),
              //                  BiGetType.BI_GET_TYPE_60.getIndex(),
              //                  BiType.BI_TYPE_300.getIndex(),
              //                  BiChuOrRu.BI_CHU_OR_RU_1.getIndex(),
              //                  levelUpPrice_k5,
              //                  null);
              //              userInfoService.updateEntity(tempUser);
            }
            break;
        }
      }
    }
    logger.info("===userLeveUp===end");
  }
}
